//定义store
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userLoginAPI, newUserInfoAPI } from '@/apis/user'
import { useCartStore } from './cartStore'
import { mergeCartAPI } from '@/apis/cart'
import { useAddressStore } from './addressStore'
export const useUserStore = defineStore('user', () => {
    const cartStore = useCartStore()
    const addressStore = useAddressStore()
    //有点像javaBean
    //1.定义属性
    //2.定义属性的方法
    //3.决定暴露出去的接口
    //导航列表的数据管理
    //state 导航列表数据
    const userInfo = ref({})
    //action获取导航数据的方法
    const getUserInfo = async ({ username, password }) => {
        const res = await userLoginAPI({ username, password })
        userInfo.value = res.data;
        
        if (userInfo.value.code == 0) {
            //登录时：合并购物车
            //根据一个现有的数组，处理后得到新的数组，用map方法
            await mergeCartAPI(cartStore.cartList.map(item => {
                return {
                    goodsId: item.goodsId,
                    count: item.count
                }
            }))
            cartStore.updateNewList()
            //登录时：获取用户地址
            addressStore.getAddressInfo()
        }

    }
    const clearUserInfo = async () => {
        userInfo.value = {}
        //执行清除购物车的action 
        // - 下面这行用不到，在退出登录按钮那里已经用过了
        //cartStore.clearCart()
        //执行清除用户地址的action 
        addressStore.clearAddressInfo()
    }

    const getNewUserInfo = async () => {
        const res = await newUserInfoAPI()
        userInfo.value.data.user = res.data.data
    }

    return {
        userInfo,
        getUserInfo,
        clearUserInfo,
        getNewUserInfo,
    }
}, {
    persist: true//持久化存储
})